package com.sky.service.admin.impl;

import com.sky.constant.MessageConstant;
import com.sky.dto.ReportSelectDTO;
import com.sky.entity.Orders;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.admin.OrdersMapper;
import com.sky.mapper.admin.ReportMapper;
import com.sky.mapper.user.OrderDetailMapper;


import com.sky.service.admin.ReportService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;


@Slf4j
@Service("adminReportService")
public class ReportServiceImpl implements ReportService {


    @Autowired
    private ReportMapper reportMapper;


    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WorkSpaceServiceImpl adminWorkSpaceService;

    /**
     * 用户统计接口
     * @return
     */
    @Override
    public UserReportVO userStatistics(ReportSelectDTO reportSelectDTO) {

        // 查询日期列表
        ArrayList<LocalDate> dateList = new ArrayList<>();
        // 获取开始时间和结束时间
        dateList.add(reportSelectDTO.getBegin());
        LocalDate begin = reportSelectDTO.getBegin();
        LocalDate end = reportSelectDTO.getEnd();

        // 遍历日期
        while (begin.isBefore(end)){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }

        List<String> newUserList = new ArrayList<>();
        List<String> totalUserList = new ArrayList<>();
        Long totalUser = 0L;

        for (LocalDate date : dateList) {
            // 获取每日开始时间和结束时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            // 构造查询条件
            Map<Object, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);

            String count = reportMapper.newUserList(map);
            // 查询每日新增用户数
            newUserList.add(count);

            // 查询总用户量、逗号分隔
            totalUser += Integer.parseInt(count);
            totalUserList.add(totalUser.toString());
        }
//        log.warn("每日新用户数量{}",newUserList);
//        log.warn("总用户数{}",totalUser);

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, " ,"))
                .build();
    }

    /**
     * 营业额统计接口
     * @param reportSelectDTO
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(ReportSelectDTO reportSelectDTO) {
        // 获取日期列表
        LocalDate begin = reportSelectDTO.getBegin();
        LocalDate end = reportSelectDTO.getEnd();
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        // 遍历日期
        while (begin.isBefore(end)){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }

        List<String> turnoverList = new ArrayList<>();
        // 遍历日期获取营业额列表
        for (LocalDate date : dateList) {
            //构造开始和结束时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<Object, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status",Orders.COMPLETED);
            String count = reportMapper.turnover(map);
            // 如果值为null，则赋值为0
            if (count == null){
                count = "0";

            }
            turnoverList.add(count);
        }
        log.info("查询到的营业额列表为{}", turnoverList);
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 订单统计接口
     * @param reportSelectDTO
     * @return
     */
    @Override
    public OrderReportVO orderStatistics(ReportSelectDTO reportSelectDTO) {
        // 日期列表
        LocalDate begin = reportSelectDTO.getBegin();
        LocalDate end = reportSelectDTO.getEnd();
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (begin.isBefore(end)){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }

       Integer validOrderCount = 0;
       Integer totalOrderCount = 0;
        double orderCompletionRate = 0;
        String orderCountList = null;
        String validOrderCountList = null;


        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<Object, Object> map = new HashMap<>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);


            // 每日订单总数
            totalOrderCount = ordersMapper.orderCount(map);


            // 订单数列表
            List<String> orderCountListElement = ordersMapper.orderCountList(map);
            orderCountList = StringUtils.join(orderCountListElement, ",");


            // 每日有效订单数
            map.put("status", Orders.COMPLETED);
            validOrderCount = ordersMapper.orderCount(map);


            // 有效订单数列表
            List<String> validOrderCountListElement = ordersMapper.orderCountList(map);
            validOrderCountList = StringUtils.join(validOrderCountListElement, ",");


            // 订单完成率
            try{
                orderCompletionRate = validOrderCount * 1.0 / totalOrderCount;
            }catch (OrderBusinessException e){
                log.error(MessageConstant.ORDER_NOT_FOUND, e.getMessage());
            }

        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ""))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(orderCountList)
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .validOrderCountList(validOrderCountList)
                .build();
    }

    /**
     * 查询销量排名top10接口
     * @param reportSelectDTO
     * @return
     */
    @Override
    public SalesTop10ReportVO queryTheTopTenSales(ReportSelectDTO reportSelectDTO) {
        // 构造查询对象
        LocalDateTime beginTime = LocalDateTime.of(reportSelectDTO.getBegin(), LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(reportSelectDTO.getEnd(), LocalTime.MAX);
        Map<Object, Object> map = new HashMap<>();
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        log.warn("打印查询参数{}",map);
        List<Map<String, Long>> queryTheTopTenSales = orderDetailMapper.queryTheTopTenSales(map);
        log.warn("打印map查询的结果{}", queryTheTopTenSales);

        // 构造nameList 商品名称列表
        List<String> nameList = new ArrayList<>();
        // 构造numberList 销量列表
        List<String> numberList = new ArrayList<>();

        for (Map<String, Long> result : queryTheTopTenSales) {
            nameList.add(String.valueOf(result.get("name")));
            numberList.add(String.valueOf(result.get("number")));
        }
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 导出报表相关接口
     */
    @Override
    public void export(HttpServletResponse httpServletResponse) {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);

        BusinessDataVO businessDataVO = adminWorkSpaceService.businessData(begin, end);
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/OperatorDataReport.xlsx");
        // todo zip io 错误
        if (resourceAsStream != null) {
            try (XSSFWorkbook workbook = new XSSFWorkbook(resourceAsStream);
                 ServletOutputStream outputStream = httpServletResponse.getOutputStream()) {

                XSSFSheet sheet1 = workbook.getSheet("sheet1");
                sheet1.getRow(1).getCell(1).setCellValue(begin + " ~ " + end);

                int firstRowNum = sheet1.getFirstRowNum();
                int lastRowNum = sheet1.getLastRowNum();

                double allTurnover = 0.0;
                double allOrderCompletionRate = 0.0;
                int allValidOrderCount = 0;
                double allUnitPrice = 0.0;
                int allNewUsers = 0;

                while (firstRowNum <= lastRowNum) {
                    XSSFRow row = sheet1.getRow(firstRowNum);
                    LocalDate currentDate = begin.plusDays(firstRowNum);
                    row.getCell(0).setCellValue(currentDate.toString());

                    // 设置明细数据
                    row.getCell(1).setCellValue(businessDataVO.getTurnover());
                    row.getCell(2).setCellValue(businessDataVO.getOrderCompletionRate());
                    row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                    row.getCell(4).setCellValue(businessDataVO.getUnitPrice());
                    row.getCell(5).setCellValue(businessDataVO.getNewUsers());

                    allTurnover += businessDataVO.getTurnover();
                    allOrderCompletionRate += businessDataVO.getOrderCompletionRate();
                    allValidOrderCount += businessDataVO.getValidOrderCount();
                    allUnitPrice += businessDataVO.getUnitPrice();
                    allNewUsers += businessDataVO.getNewUsers();

                    firstRowNum++;
                }

                // 设置概览数据
                int averageOrderCompletionRate = (int) (allOrderCompletionRate / 30);
                XSSFRow rowFour = sheet1.getRow(3);
                rowFour.getCell(1).setCellValue(allTurnover);
                rowFour.getCell(3).setCellValue(averageOrderCompletionRate);
                rowFour.getCell(5).setCellValue(allNewUsers);

                XSSFRow rowFive = sheet1.getRow(4);
                rowFive.getCell(1).setCellValue(allValidOrderCount);
                rowFive.getCell(3).setCellValue(allUnitPrice);

                // 下载文件到浏览器
                httpServletResponse.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                httpServletResponse.setHeader("Content-Disposition", "attachment; filename=OperatorDataReport.xlsx");
                workbook.write(outputStream);

            } catch (IOException e) {
                log.error("数据导出功能异常", e);
            }
        }
    }


}

